<template>
  <div>
    <Tips />
    <CartList :getCartDBList="getCartDBList" />
    <Submit :getCartDBList="getCartDBList" :allCheckAction="allCheckAction" />
  </div>
</template>

<script>
import Tips from "@/components/Tips.vue";
import { mapGetters } from "vuex";
import CartList from "./CartList.vue";
import Submit from "./Submit.vue";
export default {
  name: "cart",
  data() {
    return {
      checked: true,
    };
  },
  components: { Tips, CartList, Submit },
  mounted() {
    this.$store.dispatch("getCartInfo");
    // 更改单个item状态
    this.$bus.$on("changeItemState", this.changeItemState);
  },
  beforeDestroy() {
    this.$bus.$off("changeItemState");
  },
  computed: {
    ...mapGetters(["getCartDBList"]),
  },
  methods: {
    // 全选操作
    allCheckAction(flag) {
      this.getCartDBList.forEach((element) => {
        element.checked = flag;
        this.$store.dispatch("alertCartDB", {
          cartId: element.id,
          num: element.num,
          checked: element.checked,
        });
      });
    },
    // 更改单个item状态
    changeItemState(id) {
      this.getCartDBList.forEach((element) => {
        if (element.id == id) {
          element.checked = !element.checked;
          this.$store.dispatch("alertCartDB", {
            cartId: element.id,
            num: element.num,
            checked: element.checked,
          });
        }
      });
    },
  },
  watch: {
    getCartDBList: {
      handler() {
        let count = 0;
        this.getCartDBList.forEach((element) => {
          if (element.checked) {
            count++;
          }
        });

        if (count == this.getCartDBList.length) {
          // 更改全选状态
          this.$bus.$emit("changeAllState", true);
        } else {
          this.$bus.$emit("changeAllState", false);
        }
      },
      deep: true,
    },
  },
};
</script>


<style scoped lang='less'>
</style>